﻿Imports WPFGlue.Framework

Namespace Commanding
    <System.Windows.Markup.ContentProperty("Commands"), System.Windows.Markup.NameScopeProperty("NameScope")>
Public Class CommandSet
        Inherits CommandBase

        Public Sub New()
            Commands = New CommandCollection
        End Sub
        Private Shared ReadOnly CommandsPropertyKey As DependencyPropertyKey = DependencyProperty.RegisterReadOnly("Commands", GetType(CommandCollection), GetType(CommandSet), New PropertyMetadata())
        Public Shared ReadOnly CommandsProperty As DependencyProperty = CommandsPropertyKey.DependencyProperty
        Public Property Commands As CommandCollection
            Get
                Return GetValue(CommandsProperty)
            End Get
            Private Set(ByVal value As CommandCollection)
                SetValue(CommandsPropertyKey, value)
            End Set
        End Property

        Protected Overrides Sub Attach(ByVal base As Object)

            For Each command As IStickyComponent In Commands
                command.OnAttach(base, System.EventArgs.Empty)
            Next

        End Sub

        Protected Overrides Function CreateInstanceCore() As System.Windows.Freezable
            Return New CommandSet
        End Function

        Protected Overrides Sub Detach(ByVal base As Object)
            For Each command As IStickyComponent In Commands
                command.OnDetach(base, System.EventArgs.Empty)
            Next
        End Sub

        Public Overrides Function FindName(name As String) As CommandBase
            Return Commands.Item(name)
        End Function
    End Class

    Public Class CommandCollection
        Inherits FreezableCollection(Of CommandBase)

        Default Public Overloads ReadOnly Property Item(ByVal name As String) As CommandBase
            Get
                Dim result As CommandBase = Nothing
                For Each c As CommandBase In Me
                    result = c.FindName(name)
                    If result IsNot Nothing Then
                        Exit For
                    End If
                Next
                Return result
            End Get
        End Property


    End Class

End Namespace

